package com.buddies.lottery.ui.entry;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AlertDialog;

import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseActivity;
import com.buddies.lottery.common.ConfigManager;
import com.buddies.lottery.data.resp.LotteryConfigResponse;
import com.buddies.lottery.ui.MainActivity;
import com.buddies.lottery.ui.login.LoginActivity;
import com.buddies.lottery.utils.PermissionUtils;
import com.buddies.lottery.utils.SystemUtils;

public class EntryActivity extends BaseActivity<EntryContract.Presenter> implements EntryContract.View {

    private static final int REQUEST_PERMISSIONS = 10001;
    private boolean hasPause = true;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_entry;
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        // 解决安装完成之后，点击“打开”按钮，然后按“Home”键点击桌面ICON重新打开新的Activity
        if (!isTaskRoot()) {
            Intent intent = getIntent();
            String action = intent.getAction();
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) {
                finish();
                return;
            }
        }

        mPresenter = new EntryPresenter(this);
        mPresenter.loadLotteryConfig();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (hasPause) {
            checkPermissions();
        }
    }

    private void checkPermissions() {
        if (PermissionUtils.checkPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                && PermissionUtils.checkPermission(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
            toNext();
        } else {
            PermissionUtils.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE}, REQUEST_PERMISSIONS);
        }
    }

    private void toNext() {
        postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!ConfigManager.getInstance().isLogin()) {
                    LoginActivity.launch(getActivity());
                } else {
                    MainActivity.launch(getActivity());
                }
                finish();
            }
        }, 1200);
    }

    @Override
    protected void onStop() {
        super.onStop();
        hasPause = true;
    }

    @Override
    public void onLotteryConfigLoaded(LotteryConfigResponse response) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (requestCode == REQUEST_PERMISSIONS) {
                if ((grantResults.length > 0 && grantResults[0] != PermissionChecker.PERMISSION_GRANTED) ||
                        (grantResults.length > 1 && grantResults[1] != PermissionChecker.PERMISSION_GRANTED)) {

                    String appName = getString(R.string.app_name);
                    String tips = appName + "使用「存储、电话」权限确定设备ID，以保证账号登录的安全性。" + appName +
                            "不会拨打其他号码或终止通话。请在设置-应用-" + appName + "-权限中开启「存储、电话」权限，以正常使用App功能";

                    new AlertDialog.Builder(this)
                            .setMessage(tips)
                            .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    SystemUtils.jumpAppDetailSettings(getActivity());
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            })
                            .create()
                            .show();

                    hasPause = false;
                } else {
                    hasPause = true;
                }
            }
        }
    }

    public static void launch(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, EntryActivity.class);
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

}
